//
//  WMTrainingController.m
//  ChannelSoftWeMarketing
//
//  Created by channelsoftios on 17/7/31.
//  Copyright © 2017年 channelsoftios. All rights reserved.
//

#import "WMHTMLViewController.h"
#import "WMHTMLView.h"
#import "SettingPaymentPwdViewController.h"
#import "ZFPwdView.h"
#import "UserManager.h"
#import "JHUIAlertView.h"
#import "LoginManager.h"
#import "WCAddrEditVC.h"

@interface WMHTMLViewController ()<WKUIDelegate,WKNavigationDelegate>

@property (strong, nonatomic) JHUIAlertView *alertView;
@property (strong, nonatomic) WKWebView *webView;
@property (strong, nonatomic) UITextField *rechargeTF;
@property (copy, nonatomic) NSString *alertMessage;

@end

@implementation WMHTMLViewController

- (instancetype)init {
    if (self = [super init]) {
        self.showProgressView = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = kLocalizedString(@"商品详情", nil);
    
    if (self.hideLeftItem) {
        self.navigationItem.hidesBackButton   = YES;
        self.navigationItem.leftBarButtonItem = nil;
    }
    
    _webView = [[WKWebView alloc] initWithFrame:self.webViewRect];
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.htmlUrl]]];
    
    _webView.scrollView.scrollEnabled = self.canScroll;
    _webView.UIDelegate = self;
    _webView.navigationDelegate = self;
    
    [self.view addSubview:_webView];
    
    if (@available(ios 11.0,*)) {
        _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
}

#pragma mark - WKNavigationDelegate
- (void)closeView {
    [self.alertView dismiss];
    [self.view endEditing:YES];
}

- (void)buttonEvent {
    NSString *password = self.rechargeTF.text;
    if (password.length <= 0) {
        [HFStatusView showFailureMessage:kLocalizedString(@"请输入支付密码", nil)];
        return;
    }
    [self.view endEditing:YES];
    [self.alertView dismiss];
 
    @weak(self);
    //转账
    NSData *jsonData = [self.alertMessage dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",dic);
    NSLog(@"%@",self.alertMessage);
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    [params setObject:[CBTLocalUserManager sharedInstance].userId forKey:@"userId"];
    [params setObject:dic[@"num"] forKey:@"num"];
    [params setObject:dic[@"colorId"] forKey:@"colourId"];
    [params setObject:dic[@"coinId"] forKey:@"coinId"];
    [params setObject:dic[@"day"] forKey:@"day"];
    [params setObject:password forKey:@"jyPassword"];

    //检查是否设置过支付密码、是否实名认证
    NSString *area = [[NSUserDefaults standardUserDefaults] objectForKey:@"area"];
    [LoginManager phoneaAndEmailLoginWithID:[NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone] ? [CBTLocalUserManager sharedInstance].userEmail : [CBTLocalUserManager sharedInstance].userPhone isPhone:![NSString isBlankString:[CBTLocalUserManager sharedInstance].userPhone]  pwd:HEFANTV_UserPassWord area:area block:^(id data, HttpRequestResult result, NSString *msg) {
        if (result == kHttpRequestResultNormal) {
            
            [[NSUserDefaults standardUserDefaults]setObject:[data[@"data"]objectForKey:@"token"] forKey:HEFANTV_TOKEN];
            [[NSUserDefaults standardUserDefaults]synchronize];
            [[CBTLocalUserManager sharedInstance] saveALLUserInfoDic:data];
            
            [self_weak_ stopLoading];
            if ([[data[@"data"]objectForKey:@"status"]intValue] == 0) {
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:kLocalizedString(@"请先设置支付密码", nil) message:@"" preferredStyle:UIAlertControllerStyleAlert];
                    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:kLocalizedString(@"确认",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                    UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
                    SettingPaymentPwdViewController *vc = [story instantiateViewControllerWithIdentifier:@"SettingPaymentID"];
                    [self.navigationController pushViewController:vc animated:YES];
                }];
                [alertController addAction:confirmAction];
                [self presentViewController:alertController animated:YES completion:nil];
            }
            else {
                [UserManager userDoPCChangeWithUserInfo: params block:^(id data, HttpRequestResult result, NSString *msg) {
                    [self_weak_ stopLoading];
                    
                    if (result == kHttpRequestResultNormal) {
                        [HFStatusView showSuccessMessage:msg];
                        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC));
                        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                            [self_weak_.navigationController popViewControllerAnimated:YES];
                        });
                    }
                    else {
                        if ([data[@"code"] intValue] == -1065) {
                            UIAlertController *alertController = [UIAlertController alertControllerWithTitle:msg message:@"" preferredStyle:UIAlertControllerStyleAlert];
                            UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:kLocalizedString(@"确认",nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                                WCAddrEditVC *vc = [[WCAddrEditVC alloc] init];
                                [self.navigationController pushViewController:vc animated:YES];
                            }];
                            [alertController addAction:confirmAction];
                            [self presentViewController:alertController animated:YES completion:nil];
                        }
                        else {
                            [HFStatusView showSuccessMessage:msg];
                        }
                    }
                }];
            }
        }
        else {
            [HFStatusView showFailureMessage:kLocalizedString(@"网络异常，请稍后重试",nil)];
        }
    }];
}

- (void)payOrderWithMessage:(NSString *)message {
    
    self.alertMessage = message;
    
    JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
    
    config.title.text  = kLocalizedString(@"校验支付密码", nil);
    config.title.color = UIColorFromRGB(0xff5101);
    config.title.bottomPadding = 100;
    config.dismissWhenTapOut   = NO;
    config.contentViewWidth    = SCREEN_WIDTH*0.8;
    config.contentViewHeight   = 180;
    self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
    
    __weak typeof(self)weakself = self;
    [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
        
        UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
        closebtn.tintColor = [UIColor blackColor];
        [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
        [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
        closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
        [alertView.contentView addSubview:closebtn];
        
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 40)];
        textField.secureTextEntry = YES;
        textField.backgroundColor = UIColorFromRGB(0xEAEAEA);
        textField.keyboardType    = UIKeyboardTypeNumberPad;
        textField.layer.cornerRadius = 5;
        [alertView.contentView addSubview:textField];
        weakself.rechargeTF = textField;
        weakself.rechargeTF.placeholder = kLocalizedString(@"请输入支付密码", nil);
        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
        button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+24, contentViewRect.size.width-30, 40);
        button.titleLabel.font = [UIFont systemFontOfSize:16];
        [button setTitle:kLocalizedString(@"确定", nil) forState:0];
        [button setTitleColor:[UIColor whiteColor] forState:0];
        button.layer.cornerRadius = 5;
        button.backgroundColor = UIColorFromRGB(0xff5001);
        [button addTarget:weakself action:@selector(buttonEvent) forControlEvents:1<<6];
        [alertView.contentView addSubview:button];
        
    }];
    
    [self.view addSubview:self.alertView];
}

//! alert(message)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self payOrderWithMessage:message];
        completionHandler();
    });
    
}

//- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
//
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Confirm" message:message preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(NO);
//    }];
//    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(YES);
//    }];
//    [alertController addAction:cancelAction];
//    [alertController addAction:confirmAction];
//    [self presentViewController:alertController animated:YES completion:nil];
//}
//
////! prompt(prompt, defaultText)
//- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
//
//    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
//    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
//        textField.placeholder = defaultText;
//    }];
//    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        completionHandler(alertController.textFields[0].text);
//    }];
//    [alertController addAction:confirmAction];
//    [self presentViewController:alertController animated:YES completion:nil];
//}

@end
